package com.gaoshi.chapter4;

/**
 * This program demonstrates parameter passing in Java.
 * 演示值传递
 */
public class ParamTest {
    public static void main(String[] args) {
        // Test1: Methods can't modify numeric parameters
        System.out.println("Testing tripleValue:");
        double percent = 10;
        System.out.println("Before: percent=" + percent);
        tripleValue(percent);
        System.out.println("After:  percent=" + percent);

        // Test2: Method can change the state of object parameters
        System.out.println("\nTesting tripleSalary:");
        EmployeeParam harry = new EmployeeParam("Harry", 50000);
        System.out.println("Before: salary=" + harry.getSalary());
        tripleSalary(harry);
        System.out.println("After:  salary=" + harry.getSalary());

        // Test3: Methods can't attach new objects to object parameters
        System.out.println("\nTesting swap:");
        EmployeeParam a = new EmployeeParam("Alice", 70000);
        EmployeeParam b = new EmployeeParam("Bob", 60000);
        System.out.println("Before: a=" + a.toString());
        System.out.println("Before: b=" + b.toString());
        swap(a, b);
        System.out.println("After:  a=" + a.toString());
        System.out.println("After:  b=" + b.toString());
    }

    public static void tripleValue(double x) {
        x *= 3;
        System.out.println("End of metod x=" + x);
    }

    public static void tripleSalary(EmployeeParam employeeParam) {
        employeeParam.raiseSalary(200);
        System.out.println("End of method employee.salary=" + employeeParam.getSalary());
    }

    public static void swap(EmployeeParam x, EmployeeParam y) {
        EmployeeParam temp = x;
        x = y;
        y = temp;
        System.out.println("End of method x=" + x.toString());
        System.out.println("End of method y=" + y.toString());
    }
}

class EmployeeParam {  // simplified Employee class
    private String name;
    private double salary;

    public EmployeeParam(String n, double s) {
        name = n;
        salary = s;
    }

    public String getName() {
        return name;
    }

    public double getSalary() {
        return salary;
    }

    public void raiseSalary(double byPercent) {
        salary += salary * byPercent / 100;
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder("EmployeeParam{");
        sb.append("name='").append(name).append('\'');
        sb.append(", salary=").append(salary);
        sb.append('}');
        return sb.toString();
    }
}
